package com.myrpc.consumer.utils;

import java.util.Map;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
 * 
 * @author laichunhua
 * SpringContext 工具类
 */
@Component
public class SpringContextHolder implements ApplicationContextAware {

	private static ApplicationContext applicationContext;
	@Override
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		SpringContextHolder.applicationContext = applicationContext;
	}
	
	public static ApplicationContext getApplicationContext() {
		return applicationContext;
	}
	
	
	/**
     * 根据bean的id来查找对象
     * @param id
     * @return
     */
    public static Object getBeanById(String id){
        return applicationContext.getBean(id);
    }
	
	/**
     * 根据bean的class来查找对象
     * @param c
     * @return
     */
    public static Object getBeanByClass(Class c){
        return applicationContext.getBean(c);
    }
     
	
	/**
     * 根据bean的class来查找所有的对象(包括子类)
     * @param c
     * @return
     */
    public static Map getBeansByClass(Class c){
        return applicationContext.getBeansOfType(c);
    }
 
	
	/**
	 * 打印出所有的Bean对象，包括Springboot本身加载的Bean
	 * 可以通过AOP自定义注解只加载业务中的Bean对象，后期可以优化
	 */
	public void printAllBeans() {
		String[] beans = SpringContextHolder.getApplicationContext()
				.getBeanDefinitionNames();
		for (String beanName : beans) {
			Class<?> beanType = SpringContextHolder.getApplicationContext()
					.getType(beanName);
			
			System.out.println("beanType.getName:" + beanType.getName());
			System.out.println("BeanName:" + beanName);
			System.out.println("Bean的类型：" + beanType);
			System.out.println("Bean所在的包：" + beanType.getPackage());
			System.out.println("Bean：" + SpringContextHolder.getApplicationContext().getBean(
					beanName));
		}
	}


}
